export default class SocketService {

  ws = null
  type = '';
  connected = false
  // 发送失败之后尝试的次数
  sendTryCount = 0
  // 连接失败之后尝试的次数
  connectTryCount = 0
  // 回调函数
  callBackMapping = {}

  registerCallBack = (type, callBackFunc) => {
    console.log("注册函数");
    this.type = type;
    this.callBackMapping[type] = callBackFunc

    console.log(type);

    console.log("注册：" + this.callBackMapping[type]);
  }

  unRegisterCallBack = type => {
    console.log(type + "删除:" + this.callBackMapping[type]);
    delete this.callBackMapping[type]

  }

  constructor(url) {
    this.wsuri = url;
    this.createWs();
  }

  createWs() {
    this.ws = new WebSocket(this.wsuri);
    // 监听事件
    this.connect();
  }

  connect() {
    if (!window.WebSocket) {
      alert('您的浏览器不支持WebSocket')
      return
    }


    this.ws.onopen = () => {
      this.connected = true
      this.connectTryCount = 0
    }

    this.ws.onclose = () => {
      console.log('连接失败，请重试...')
      this.connectTryCount++
      this.connected = false

      // 失败之后尝试连接
      // setTimeout(() => {
      //   this.connect()
      // }, this.connectTryCount * 500)
    }

    this.ws.onmessage = msg => {
      console.log("onmessage");
      let metype = this.type;
      const msgObj = JSON.parse(msg.data)
      if (this.callBackMapping[metype]) {
        this.callBackMapping[metype].call(
          this,
          msgObj
        )
      }


    }
  }

  // 发送数据给服务器
  send = data => {
    console.log("发送send数据");
    console.log(this.connected);
    if (this.connected) {
      this.sendRetryCount = 0
      this.ws.send(data)
    } else {
      this.sendTryCount++
      setTimeout(() => {
        this.send(data)
      }, this.sendTryCount * 500)
    }
  }

}